package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import com.tanhua.server.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Value("${tanhua.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果本次请求中没有携带token，返回401状态码
        String token = request.getHeader("Authorization");
        if (token == null) {
            response.setStatus(401);
            log.info("Authorization is null");
            return false;
        }

        boolean validToken = JwtUtils.isValidToken(secret, token);
        if (!validToken) {
            response.setStatus(401);
            log.info("Authorization is incorrect: {}", token);
            return false;
        }
        User user = JwtUtils.parseToken(secret, token);
        UserHolder.setUser(user);
        UserHolder.setToken(token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
        UserHolder.removeToken();
    }

    private User findByToken(String token) {
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson != null) {
            redisTemplate.opsForValue().set("TOKEN_" + token,userJson, Duration.ofHours(1));
            return JSON.parseObject(userJson, User.class);
        }
        return null;
    }
}
